package com.sckj.springboot.exception;

import com.sckj.springboot.entity.JsonResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

@ControllerAdvice//注解异常
@ResponseBody
public class GlobalExceptionHandler {
    //打印日志
    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 请求参数异常
     **/
    @ExceptionHandler
    @ResponseStatus(value = HttpStatus.BAD_REQUEST)
    public JsonResult handleHttpMessageNotReadableException(MissingServletRequestParameterException ex){
        logger.error("缺少参数{}",ex.getMessage());
        return  new JsonResult("400","缺少必要的请求参数");
    }

    /**
     * 请求空指针异常
     **/
    @ExceptionHandler(NullPointerException.class)
    @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
    public JsonResult handleTypeMismatchException(NullPointerException ex){
        logger.info("空指针异常",ex.getMessage());
        return new JsonResult("500","空指针异常");
    }

    /**
    *自定义异常
     */
    @ExceptionHandler(BusinessErrorException.class)
    @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
    public JsonResult HandleBusinessError(BusinessErrorException ex){
        String code = ex.getCode();
        String massage = ex.getMassage();
        return new JsonResult(code,massage);
    }
}
